﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Common.Enums;
using Com.JunCaiSoft.Common.IDao;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Permission.IDao;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Org.BouncyCastle.Math.EC.Rfc7748;

namespace Com.JunCaiSoft.Common.Controller
{
    /// <summary>
    /// 实体操作基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Authorize]
    public abstract class BaseController<SingleModel,ListModel,T,TKey> : ControllerBase where T : class, new()
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dao"></param>
        protected BaseController(IGeneralDaoAsync<T> dao)
        {
            DaoAsync = dao;
        }
        /// <summary>
        /// 数据库操作层
        /// </summary>
        protected IGeneralDaoAsync<T> DaoAsync { get; }
        /// <summary>
        /// 获取编码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> CreateCode()
        {
            try
            {
                Int64 result = TimeStamp.timestamp;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取单个实体
        /// </summary>
        /// <param name="Id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> GetAsync(TKey Id)
        {
            try
            {
                var getOne = (await DaoAsync.GetAsync<T>(Id)).MapTo<SingleModel>();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(getOne)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 增加单个实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ActionResult> CreateAsync(SingleModel entity)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                var result = await DaoAsync.InsertAsync(entity.MapTo<T>());

                await DaoAsync.dbContext.Database.CommitTransactionAsync();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }
        }
        /// <summary>
        /// 删除单个实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public virtual async Task<ActionResult> DeleteSingleAsync(TKey Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                if (typeof(TKey) == typeof(Guid) ? Guid.Parse(Id.ToString()) != Guid.Empty : Id != null)
                {
                    var getOne = await DaoAsync.GetAsync<T>(Id);
                    var result = await DaoAsync.DeleteAsync(getOne);

                    await DaoAsync.dbContext.Database.CommitTransactionAsync();
                    return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
                }
                else
                {
                    return await Task.Run(() => Content(JsonConvert.SerializeObject(0)));
                }
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }
        }
        /// <summary>
        /// 更新单个实体
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public virtual async Task<ActionResult> UpdateAsync(UpdateEntity<SingleModel> entityModel)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                var result = await DaoAsync.UpdateAsync(entityModel.entity.MapTo<T>(), entityModel.Id);

                await DaoAsync.dbContext.Database.CommitTransactionAsync();

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();

                throw e;
            }
        }
        [HttpGet]
        public virtual async Task<ActionResult> EntityList(String keyword)
        {
            try
            {
                List<ListModel> returnList = new List<ListModel>();

                var entitylist = (await DaoAsync.ListAsync());

                entitylist.ForEach(item =>
                {
                    returnList.Add(item.MapTo<ListModel>());
                });

                return await Task.Run(() => Content(JsonConvert.SerializeObject(returnList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
